package com.melody.rest.service.impl;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.melody.rest.domain.RestSysUser;
import com.melody.rest.model.ResultCode;
import com.melody.rest.model.ResultJson;
import com.melody.rest.service.RestAuthService;
import com.melody.rest.util.ResourceVerification;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;


import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;


@Service
public class RestAuthServiceImpl implements RestAuthService {

    @Autowired
    RedisTemplate redisTemplate;


    @Override
    public ResultJson Login(RestSysUser restSysUser) {
        //账号密码校验，
        if("admin".equals(restSysUser.getUsername()) && "123456".equals(restSysUser.getPassword())){
            //账号密码正确
            //登录成功
            restSysUser.setResources(ResourceVerification.resource());
            Map<String, Object> userMap = BeanUtil.beanToMap(restSysUser, new HashMap<>(),
                    CopyOptions.create()
                            .setIgnoreNullValue(true)//忽略一些空值
                            .setFieldValueEditor((fieldName, fieldValue) -> fieldValue.toString()));
            UUID uuid = UUID.randomUUID();
            String tokenKey= String.valueOf(uuid);
            String token="LoginUserKey "+tokenKey;
            //存储
            redisTemplate.opsForHash().putAll(token,userMap);
            //设置存值时间，expire默认秒：1天
            redisTemplate.expire(token,60*60*24, TimeUnit.MINUTES);
            return ResultJson.ok(token);
        }else{
            //账号密码不正确
            return ResultJson.failure(ResultCode.LOGIN_ERROR);
        }
    }
}
